package com.itheima.security;

import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

@Component("springSecurityUserService")
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;//需要通过远程调用用户服务

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查找用户
        User user = userService.findUserByUserName(s);
        if (user == null) {
            //表示没有找到,即该用户权限
            return null;
        }

        //创建一个集合存放用户的权限
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //获取用户的角色
        Set<Role> roles = user.getRoles();
        //遍历角色集合
        for (Role role : roles) {
            //将角色的添加到集合中
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取当前角色的权限
            Set<Permission> permissions = role.getPermissions();
            //遍历权限结合,将每个权限存到authorities集合中级中
            for (Permission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        //创建User
        org.springframework.security.core.userdetails.User userDetail = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);

        return userDetail;
    }
}
